/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package common;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mateusz
 */
public class Framer {

    private Socket socket;

    public Framer(Socket socket) {
        this.socket = socket;
    }

    private void sendObject(Object obj){
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(obj);
        } catch (IOException ex) {
            Logger.getLogger(Framer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                oos.close();
            } catch (IOException ex) {
                Logger.getLogger(Framer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public Envelope get(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            return (Envelope) ois.readObject();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Framer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Framer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                ois.close();
            } catch (IOException ex) {
                Logger.getLogger(Framer.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }
    }

    public void sendMessage(int code, String message) {
        Envelope envelope = new Envelope(code, message);
        sendObject(envelope);
    }

    public void sendCode(int code) {
        Envelope envelope = new Envelope(code);
        sendObject(envelope);
    }

    public void sendFile(int code, File file) {
        Envelope envelope = new Envelope(code, file);
        sendObject(envelope);
    }
}
